MWF.require("MWF.widget.Common", null, false);
MWF.require("MWF.xAction.org.express.RestActions", null,false);
MWF.xDesktop.requireApp("Organization", "Selector.package", null, false);
MWF.require("MWF.widget.Identity", null,false);
MWF.xApplication.process = MWF.xApplication.process || {};
MWF.xApplication.process.Xform = MWF.xApplication.process.Xform || {};
MWF.xDesktop.requireApp("process.Xform", "Package", null, false);
MWF.xApplication.process.Xform.Form = MWF.APPForm =  new Class({
	Implements: [Options, Events],
	Extends: MWF.widget.Common,
	options: {
		"style": "default",
        "readonly": false,
		"cssPath": "",
        "macro": "FormContext",
        "parameters": null,
        "moduleEvents": ["queryLoad",
            "beforeLoad",
            "postLoad",
            "afterLoad",
            "beforeSave",
            "afterSave",
            "beforeClose",
            "beforeProcess",
            "afterProcess",
            "beforeReset",
            "afterReset",
            "beforeRetract",
            "afterRetract",
            "beforeReroute",
            "afterReroute",
            "beforeDelete"]
	},
	initialize: function(node, data, options){
		this.setOptions(options);

		this.container = $(node);
        this.container.setStyle("-webkit-user-select", "text");
		this.data = data;
		this.json = data.json;
		this.html = data.html;
		
		this.path = "/x_component_process_Xform/$Form/";
		this.cssPath = this.options.cssPath || "/x_component_process_Xform/$Form/"+this.options.style+"/css.wcss";
		this._loadCss();
		
		this.modules = [];
        this.all = {};
        this.forms = {};

        if (!this.personActions) this.personActions = new MWF.xAction.org.express.RestActions();
	},
	load: function(){
        debugger;
        if (this.app){
            if (this.app.formNode) this.app.formNode.setStyles(this.json.styles);
        }
        if (!this.businessData.control.allowSave) this.setOptions({"readonly": true});
		if (this.fireEvent("queryLoad")){
            this.fireEvent("beforeLoad");

            MWF.xDesktop.requireApp("process.Xform", "lp."+MWF.language, null, false);
	//		this.container.setStyles(this.css.container);
			this._loadBusinessData();

            if (!MWF.Macro[this.options.macro || "FormContext"]){
                MWF.require("MWF.xScript.Macro", function(){
                    this.Macro = new MWF.Macro[this.options.macro || "FormContext"](this);

                    this._loadHtml();
                    this._loadForm();
                    this._loadModules(this.node);

                    this.fireEvent("postLoad");
                    this.fireEvent("afterLoad");
                }.bind(this));
            }else{
                this.Macro = new MWF.Macro[this.options.macro || "FormContext"](this);

                this._loadHtml();
                this._loadForm();
                this._loadModules(this.node);

                this.fireEvent("postLoad");
                this.fireEvent("afterLoad");
            }
		}
	},
	_loadBusinessData: function(){
        if (!this.businessData){
            this.businessData = {
                "data": {
                    "select": "222",
                    "radio": "bbb",
                    "checkbox": ["check1", "check3"],
                    "orderData": [
                        {
                            "orderName": {"namefield": "电脑"},
                            "orderCount": {"countField": "3"},
                            "priceCount": {"priceField": "9000"}
                        },
                        {
                            "orderName": {"namefield": "路由器"},
                            "orderCount": {"countField": "2"},
                            "priceCount": {"priceField": "1000"}
                        },
                        {
                            "orderName": {"namefield": "网线"},
                            "orderCount": {"countField": "10"},
                            "priceCount": {"priceField": "200"}
                        }
                    ]

                }
            };
        }
	},
	
	_loadHtml: function(){
		this.container.set("html", this.html);
		this.node = this.container.getFirst();
        this.node.setStyle("overflow", "hidden");
        this.node.addEvent("selectstart", function(e){
            var select = "text";
            if (e.target.getStyle("-webkit-user-select")){
                select = e.target.getStyle("-webkit-user-select").toString().toLowerCase();
            }

            if (select!=="text" && select!=="auto") e.preventDefault();
        });
	},
	
	_loadForm: function(){
		this._loadStyles();
		this._loadCssLinks();
		this._loadScriptSrc();
		this._loadJsheader();
		this._loadEvents();
	},
	_loadStyles: function(){
		this.node.setStyles(this.json.styles);
	},
	_loadCssLinks: function(){
		var urls = this.json.cssLinks;
		urls.each(function(url){
			new Element("link", {
				"rel": "stylesheet",
				"type": "text/css",
				"href": url
			}).inject($(document.head));
		});
	},
	_loadScriptSrc: function(){
		var urls = this.json.scriptSrc;
		urls.each(function(url){
			new Element("script", {
				"src": url
			}).inject($(document.head));
		});
	},
	_loadJsheader: function(){
		var code = this.json.jsheader.code;
		if (code) Browser.exec(code);
	},
	_loadEvents: function(){
		Object.each(this.json.events, function(e, key){
			if (e.code){
                if (this.options.moduleEvents.indexOf(key)!==-1){
                    this.addEvent(key, function(event){
                        return this.Macro.fire(e.code, this, event);
                    }.bind(this));
                }else{
                    if (key==="load"){
                        this.addEvent("postLoad", function(){
                            return this.Macro.fire(e.code, this);
                        }.bind(this));
                    }else if (key==="submit"){
                        this.addEvent("beforeProcess", function(){
                            return this.Macro.fire(e.code, this);
                        }.bind(this));
                    }else{
                        this.node.addEvent(key, function(event){
                            return this.Macro.fire(e.code, this, event);
                        }.bind(this));
                    }
                }
			}
		}.bind(this));
	},
	
	
	_getDomjson: function(dom){
		var mwfType = dom.get("MWFtype");
		switch (mwfType) {
			case "form": 
				return this.json;
			case "":
				return null;
			default:
				var id = dom.get("id");
				if (!id) id = dom.get("MWFId");
				if (id){
					return this.json.moduleList[id];
				}else{
					return null;
				}
		}
	},
	_getModuleNodes: function(dom){
		var moduleNodes = [];
		var subDom = dom.getFirst();
		while (subDom){
			if (subDom.get("MWFtype")){
                var type = subDom.get("MWFtype");
				if (type.indexOf("$")===-1){
                    moduleNodes.push(subDom);
                }
				if (subDom.get("MWFtype") !== "datagrid" && subDom.get("MWFtype") !== "subSource"){
					moduleNodes = moduleNodes.concat(this._getModuleNodes(subDom));
				}
			}else{
				moduleNodes = moduleNodes.concat(this._getModuleNodes(subDom));
			}
			subDom = subDom.getNext();
		}
		return moduleNodes;
	},

	_loadModules: function(dom){
        //var subDom = this.node.getFirst();
        //while (subDom){
        //    if (subDom.get("MWFtype")){
        //        var json = this._getDomjson(subDom);
        //        var module = this._loadModule(json, subDom);
        //        this.modules.push(module);
        //    }
        //    subDom = subDom.getNext();
        //}

		var moduleNodes = this._getModuleNodes(dom);
        //alert(moduleNodes.length);

		moduleNodes.each(function(node){
			var json = this._getDomjson(node);
			var module = this._loadModule(json, node);
			this.modules.push(module);
		}.bind(this));
	},
	_loadModule: function(json, node, beforeLoad){
		var module = new MWF["APP"+json.type](node, json, this);
        if (beforeLoad) beforeLoad.apply(module);
        if (!this.all[json.id]) this.all[json.id] = module;
        if (module.field){
            if (!this.forms[json.id]) this.forms[json.id] = module;
        }
        module.readonly = this.options.readonly;
		module.load();
		return module;
	},
    getData: function(){
        var data= Object.clone(this.businessData.data);
        Object.each(this.forms, function(module, id){
            if (module.json.section==="yes"){
                data[id] = this.getSectionData(module, data[id]);
            }else{
                data[id] = module.getData();
            }
        }.bind(this));

        this.businessData.data = data;
        this.Macro.environment.setData(this.businessData.data);
        return data;
    },
    getSectionData: function(module, obj){
        var v = module.getData();
        switch (module.json.sectionBy){
            case "person":
                return this.getSectionDataByPerson(v, obj);
                break;
            case "department":
                return this.getSectionDataByDepartment(v, obj);
                break;
            case "activity":
                return this.getSectionDataByPActivity(v, obj);
                break;
            case "script":
                return this.getSectionDataByScript(module.json.sectionByScript.code, v, obj);
                break;
            default:
                return v;
        }
    },
    getSectionDataByPerson: function(v, obj) {
        var key = layout.desktop.session.user.id;
        if (!obj || (typeOf(obj)!=="object")) obj={};
        obj[key] = v;
        return obj;
    },
    getSectionDataByDepartment: function(v, obj) {
        var key = (this.businessData.task) ? this.businessData.task.department : "";
        if (!obj || (typeOf(obj)!=="object")) obj={};
        if (key) obj[key] = v;
        return obj;
    },
    getSectionDataByPActivity: function(v, obj) {
        var key = (this.businessData.work) ? this.businessData.work.activity : "";
        if (!obj || (typeOf(obj)!=="object")) obj={};
        if (key) obj[key] = v;
        return obj;
    },
    getSectionDataByScript: function(code, v, obj) {
        var key = this.form.Macro.exec(code, this);
        if (!obj || (typeOf(obj)!=="object")) obj={};
        if (key) obj[key] = v;
        return obj;
    },

    saveWork: function(callback){
        if (this.businessData.control["allowSave"]){
            this.fireEvent("beforeSave");
            this.workAction.saveData(function(json){
                this.notice(MWF.xApplication.process.Xform.LP.dataSaved, "success");
                if (callback) callback();
                this.fireEvent("afterSave");
            }.bind(this), null, this.businessData.work.id, this.getData());
        }else{
            MWF.xDesktop.notice("error", {x: "right", y:"top"}, "Permission Denied");
            //if (failure) failure(null, "Permission Denied", "");
        }
    },
    closeWork: function(){
        this.fireEvent("beforeClose");
        if (this.app){
            this.app.close();
        //    this.fireEvent("afterClose");
        }
    },
    addMessage: function(data){
        var content = "";
        if (data.length){
            data.each(function(work){
                var users = [];
                work.taskList.each(function(task){
                    users.push(task.person+"("+task.department+")");
                }.bind(this));

                content += "<div><b>"+MWF.xApplication.process.Xform.LP.nextActivity+"<font style=\"color: #ea621f\">"+work.fromActivityName+"</font>, "+MWF.xApplication.process.Xform.LP.nextUser+"<font style=\"color: #ea621f\">"+users.join(", ")+"</font></b></div>"
            }.bind(this));
        }else{
            content += MWF.xApplication.process.Xform.LP.workCompleted;
        }

        //data.workList.each(function(list){
        //    content += "<div><b>"+MWF.xApplication.process.Xform.LP.nextActivity+"<font style=\"color: #ea621f\">"+list.activityName+"</font>, "+MWF.xApplication.process.Xform.LP.nextUser+"<font style=\"color: #ea621f\">"+list.personList.join(", ")+"</font></b></div>"
        //}.bind(this));

        var msg = {
            "subject": MWF.xApplication.process.Xform.LP.taskProcessed,
            "content": "<div>"+MWF.xApplication.process.Xform.LP.taskProcessedMessage+"“"+this.businessData.work.title+"”</div>"+content
        };
        layout.desktop.message.addTooltip(msg);
        return layout.desktop.message.addMessage(msg);
    },
    formValidation: function(routeName, opinion){
        if (this.options.readonly) return true;
        this.Macro.environment.form.currentRouteName = routeName;
        this.Macro.environment.form.opinion = opinion;

        var flag = true;
        //flag = this.validation();
        Object.each(this.forms, function(field, key){
            field.validationMode();
            if (!field.validation(routeName, opinion)) flag = false;
        }.bind(this));
        return flag;
    },
    validation: function(routeName, opinion, processor){
        this.Macro.environment.form.currentRouteName = routeName;
        this.Macro.environment.form.opinion = opinion;
        var routeFlag = this.validationRoute(processor);
        var opinionFlag = this.validationOpinion(processor);
        return routeFlag && opinionFlag;
    },
    validationRoute: function(processor){
        if (!this.json.validationRoute) return true;
        if (!this.json.validationRoute.code) return true;
        var flag = this.Macro.exec(this.json.validationRoute.code, this);
        if (!flag) flag = MWF.xApplication.process.Xform.LP.notValidation;
        if (flag.toString()!="true"){
            this.notValidationRouteMode(flag, processor);
            return false;
        }
        return true;
    },
    validationOpinion: function(processor){
        if (!this.json.validationOpinion) return true;
        if (!this.json.validationOpinion.code) return true;
        var flag = this.Macro.exec(this.json.validationOpinion.code, this);
        if (!flag) flag = MWF.xApplication.process.Xform.LP.notValidation;
        if (flag.toString()!="true"){
            this.notValidationOpinionMode(flag, processor);
            return false;
        }
        return true;
    },
    notValidationRouteMode: function(flag, processor){
        processor.routeSelectorArea.setStyle("background-color", "#ffe9e9");
        new mBox.Notice({
            type: "error",
            position: {"x": "center", "y": "top"},
            move: false,
            target: processor.routeSelectorArea,
            delayClose: 6000,
            content: flag
        });
    },
    notValidationOpinionMode: function(flag, processor){
        processor.inputTextarea.setStyle("background-color", "#ffe9e9");
        new mBox.Notice({
            type: "error",
            position: {"x": "center", "y": "top"},
            move: false,
            target: processor.inputTextarea,
            delayClose: 6000,
            content: flag
        });
    },


    //fireRtEvent: function(type, args, delay){
    //    type = removeOn(type);
    //    var events = this.$events[type];
    //    if (!events) return this;
    //    if (!events.length) return this;
    //    var event = events[events.length-1];
    //    args = Array.from(args);
    //    if (delay) fn.delay(delay, this, args);
    //    else return fn.apply(this, args);
    //    return this;
    //},
    submitWork: function(routeName, opinion, callback, processor){
        if (!this.businessData.control["allowProcessing"]){
            MWF.xDesktop.notice("error", {x: "right", y:"top"}, "Permission Denied");
            this.app.content.unmask();
            processor.node.unmask();
            return false;
        }
        if (!this.formValidation(routeName, opinion)){
            this.app.content.unmask();
            //this.app.notice("", "error", target, where, offset);
            if (callback) callback();
            return false;
        }
        if (!this.validation(routeName, opinion, processor)){
            //this.app.content.unmask();
            processor.node.unmask();
            return false;
        }
        if (!opinion) opinion = routeName;
        this.fireEvent("beforeProcess");

        MWF.require("MWF.widget.Mask", function(){
            this.mask = new MWF.widget.Mask({"style": "desktop", "zIndex": 50000});
            this.mask.loadNode(this.app.content);

            this.fireEvent("beforeSave");
            this.workAction.saveData(function(json){
                this.businessData.task.routeName = routeName;
                this.businessData.task.opinion = opinion;

                this.fireEvent("afterSave");

                this.workAction.processTask(function(json){
                    //if (processor) processor.destroy();
                    //if (processNode) processNode.destroy();
                    if (callback) callback();
                    this.fireEvent("afterProcess");
                    //    this.notice(MWF.xApplication.process.Xform.LP.taskProcessed, "success");
                    this.addMessage(json.data);

                    if (this.app.taskObject) this.app.taskObject.destroy();

                    this.app.close();
                    //window.setTimeout(function(){this.app.close();}.bind(this), 2000);
                }.bind(this), null, this.businessData.task.id, this.businessData.task);
            }.bind(this), null, this.businessData.work.id, this.getData());

        }.bind(this));
    },
    processWork: function(){
        if (this.app.inBrowser){
            this.app.content.setStyle("height", document.body.getSize().y);
        }
        this.app.content.mask({
            "destroyOnHide": true,
            "style": this.app.css.maskNode
        });

        if (!this.formValidation("", "")){
            this.app.content.unmask();
        //    if (callback) callback();
            return false;
        }

        var processNode = this.createProcessNode();

        this.setProcessNode(processNode);

        this.showProcessNode(processNode);
    },
    createProcessNode: function(){
        var processNode = new Element("div", {"styles": this.app.css.processNode_from}).inject(this.app.content);
        processNode.position({
            relativeTo: this.app.content,
            position: "topcenter",
            edge: "topcenter"
        });
        return processNode;
    },

    setProcessNode: function(processNode){
        var _self = this;
        MWF.xDesktop.requireApp("process.Work", "Processor", function(){
            new MWF.xApplication.process.Work.Processor(processNode, this.businessData.task, {
                "onCancel": function(){
                    processNode.destroy();
                    _self.app.content.unmask();
                    delete this;
                },
                "onSubmit": function(routeName, opinion){
                    _self.submitWork(routeName, opinion, function(){
                        this.destroy();
                        processNode.destroy();
                        delete this;
                    }.bind(this), this);
                }
            })
        }.bind(this));
    },
    showProcessNode: function(processNode){
        var size = this.app.content.getSize();
        var nodeSize = processNode.getSize();

        var top = size.y/2-nodeSize.y/2-20;
        var left = size.x/2-nodeSize.x/2;
        if (top<0) top = 0;

        this.app.css.processNode.top = ""+top+"px";
        this.app.css.processNode.left = ""+left+"px";

        var morph = new Fx.Morph(processNode, {
            "duration": 300,
            "transition": Fx.Transitions.Expo.easeOut
        });
        morph.start(this.app.css.processNode);
    },


    confirm: function(type, e, title, text, width, height, ok, cancel, callback){
        MWF.require("MWF.xDesktop.Dialog", function(){
            var size = this.container.getSize();

            var x = parseFloat((Browser.name==="firefox") ? e.event.clientX : e.event.x);
            var y = parseFloat((Browser.name==="firefox") ? e.event.clientY : e.event.y);

            if (x+parseFloat(width)>size.x){
                x = x-parseFloat(width);
            }
            if (x<0) x = 20;
            var dlg = new MWF.xDesktop.Dialog({
                "title": title,
                "style": "o2",
                "top": y,
                "left": x-20,
                "fromTop":e.event.y,
                "fromLeft": (Browser.name==="firefox") ? e.event.clientX-20 : e.event.x-20,
                "width": width,
                "height": height,
                "text": text,
                "container": this.content,
                "buttonList": [
                    {
                        "text": MWF.LP.process.button.ok,
                        "action": ok
                    },
                    {
                        "text": MWF.LP.process.button.cancel,
                        "action": cancel
                    }
                ]
            });

            switch (type.toLowerCase()){
                case "success":
                    dlg.content.setStyle("background-image", "url()");
                    break;
                case "error":
                    dlg.content.setStyle("background-image", "url()");
                    break;
                case "info":
                    dlg.content.setStyle("background-image", "url()");
                    break;
                case "warn":
                    dlg.content.setStyle("background-image", "url()");
                    break;
                default:
            }
            dlg.show();
        }.bind(this));
    },
    notice: function(content, type, target, where){
        if (!where) where = {"x": "right", "y": "top"};
        if (!target) target = this.node;
        if (!type) type = "ok";
        var noticeTarget = target || layout.layout.contentNode;
        new mBox.Notice({
            type: type,
            position: where,
            move: false,
            target: noticeTarget,
            delayClose: (type==="error") ? 5000 : 1000,
            offset: {
                x: 10,
                y: where.y.toString().toLowerCase()==="bottom" ? 10 : 10
            },
            content: content
        });
    },

    resetWork: function(){
        if (!this.businessData.control["allowReset"]){
            MWF.xDesktop.notice("error", {x: "right", y:"top"}, "Permission Denied");
            return false;
        }
        MWF.require("MWF.xDesktop.Dialog", function(){
            var width = 680;
            var height = 300;
            var p = MWF.getCenterPosition(this.app.content, width, height);

            var _self = this;
            var dlg = new MWF.xDesktop.Dialog({
                "title": this.app.lp.reset,
                "style": "work",
                "top": p.y-100,
                "left": p.x,
                "fromTop": p.y-100,
                "fromLeft": p.x,
                "width": width,
                "height": height,
                "url": this.app.path+"reset.html",
                "container": this.app.content,
                "isClose": true,
                "onPostShow": function(){
                    $("resetWork_okButton").addEvent("click", function(){
                        _self.doResetWork(this);
                    }.bind(this));
                    $("resetWork_cancelButton").addEvent("click", function(){
                        this.close();
                    }.bind(this));

                    $("resetWork_selPeopleButton").addEvent("click", function(){
                        _self.selectPeople(this);
                    }.bind(this));
                }
            });
            dlg.show();
        }.bind(this));
    },
    selectPeople: function(dlg){
        var range = this.businessData.activity.resetRange || "department";
        var count = this.businessData.activity.resetCount || 0;

        switch (range){
            case "department":
                this.personActions.getDepartmentByIdentity(function(json){
                    this.selectPeopleDepartment(dlg, json.data, count);
                }.bind(this), null, this.businessData.task.identity);
                break;
            case "company":
                this.personActions.getCompanyByIdentity(function(json){
                    this.selectPeopleCompany(dlg, json.data, count)
                }.bind(this), null, this.businessData.task.identity);
                break;
            default:
                this.selectPeopleAll(dlg, count);
        }
    },
    selectPeopleDepartment: function(dlg, department, count){
        var names = dlg.identityList || [];
        var areaNode = $("resetWork_selPeopleArea");
        var options = {
            "names": names,
            "type": "identity",
            "count": count,
            "departments": (department) ? [department.name]: [],
            "title": this.app.lp.reset,
            "onComplete": function (items) {
                areaNode.empty();
                var identityList = [];
                items.each(function(item){
                    var explorer = {
                        "actions": this.personActions,
                        "app": {"lp": this.app.lp}
                    };
                    new MWF.widget.Identity(item.data, areaNode, explorer, false, null, {"style": "reset"});
                    identityList.push(item.data.name);
                }.bind(this));
                dlg.identityList = identityList;
            }.bind(this)
        };

        var selector = new MWF.OrgSelector(this.app.content, options);
    },
    selectPeopleCompany: function(dlg, company, count){
        var names = dlg.identityList || [];
        var areaNode = $("resetWork_selPeopleArea");
        var options = {
            "names": names,
            "type": "identity",
            "count": count,
            "companys": [company.name],
            "title": this.app.lp.reset,
            "onComplete": function (items) {
                areaNode.empty();
                var identityList = [];
                items.each(function(item){
                    var explorer = {
                        "actions": this.personActions,
                        "app": {"lp": this.app.lp}
                    };
                    new MWF.widget.Identity(item.data, areaNode, explorer, false, null, {"style": "reset"});
                    identityList.push(item.data.name);
                }.bind(this));
                dlg.identityList = identityList;
            }.bind(this)
        };

        var selector = new MWF.Selector(this.app.content, options);
    },
    selectPeopleAll: function(dlg, count){
        var names = dlg.identityList || [];
        var areaNode = $("resetWork_selPeopleArea");
        var options = {
            "names": names,
            "type": "identity",
            "count": count,
            "title": this.app.lp.reset,
            "onComplete": function (items) {
                areaNode.empty();
                var identityList = [];
                items.each(function(item){
                    var explorer = {
                        "actions": this.personActions,
                        "app": {"lp": this.app.lp}
                    };

                    new MWF.widget.Identity(item.data, areaNode, explorer, false, null, {"style": "reset"});
                    identityList.push(item.data.name);
                }.bind(this));
                dlg.identityList = identityList;
            }.bind(this)
        };

        var selector = new MWF.Selector(this.app.content, options);
    },


    doResetWork: function(dlg){
        var names = dlg.identityList || [];
        if (!names.length){
            this.app.notice(MWF.xApplication.process.Xform.LP.inputResetPeople, "error", dlg.node);
            return false;
        }
        var opinion = $("resetWork_opinion").get("value");
        if (!opinion){
            opinion = MWF.xApplication.process.Xform.LP.resetTo+": "+names.join(", ");
        }

        MWF.require("MWF.widget.Mask", function(){
            this.mask = new MWF.widget.Mask({"style": "desktop", "zIndex": 50000});
            this.mask.loadNode(this.app.content);

            this.fireEvent("beforeReset");

            this.resetWorkToPeson(names, opinion, function(){
                this.workAction.getJobByWork(function(workJson){
                    this.fireEvent("afterReset");
                    this.addResetMessage(workJson.data);
                    this.app.notice(MWF.xApplication.process.Xform.LP.resetOk+": "+names.join(", "), "success");
                    this.app.close();
                }.bind(this), null, this.businessData.work.id);
                dlg.close();
                if (this.mask) {this.mask.hide(); this.mask = null;}
            }.bind(this), function(xhr, text, error){
                var errorText = error+":"+text;
                if (xhr) errorText = xhr.responseText;
                this.app.notice("request json error: "+errorText, "error", dlg.node);
                if (this.mask) {this.mask.hide(); this.mask = null;}
            }.bind(this));
        }.bind(this));

        //var data = {
        //    "opinion": opinion,
        //    "routeName": MWF.xApplication.process.Xform.LP.reset,
        //    "identityList": names
        //}
        //
        //this.workAction.resetWork(function(json){
        //
        //}.bind(this), null, this.businessData.task.id, data);
    },
    resetWorkToPeson: function(identityList, opinion, success, failure){
        var data = {
            "opinion": opinion,
            "routeName": MWF.xApplication.process.Xform.LP.reset,
            "identityList": identityList
        };

        this.workAction.saveData(
            function(json){
                this.workAction.resetWork(
                    function(json){
                        if (success) success();
                    }.bind(this),
                    function(xhr, text, error){
                        if (failure) failure(xhr, text, error);
                    },
                    this.businessData.task.id, data
                );
            }.bind(this),
            function(xhr, text, error){
                if (failure) failure(xhr, text, error);
            },
            this.businessData.work.id, this.getData()
        );


    },

    addResetMessage: function(data){
        var users = [];
        data.taskList.each(function(task){
            users.push(task.person+"("+task.department+")");
        }.bind(this));
        var content = "<div><b>"+MWF.xApplication.process.Xform.LP.currentActivity+"<font style=\"color: #ea621f\">"+data.work.activityName+"</font>, "+MWF.xApplication.process.Xform.LP.nextUser+"<font style=\"color: #ea621f\">"+users.join(", ")+"</font></b></div>"

        var msg = {
            "subject": MWF.xApplication.process.Xform.LP.workReset,
            "content": "<div>"+MWF.xApplication.process.Xform.LP.resetWorkInfor+"“"+this.businessData.work.title+"”</div>"+content
        };
        layout.desktop.message.addTooltip(msg);
        return layout.desktop.message.addMessage(msg);
    },

    retractWork: function(e, ev){
        var _self = this;
        var p = MWF.getCenterPosition(this.app.content, 300, 150);
        var event = {
            "event":{
                "x": p.x,
                "y": p.y-200,
                "clientX": p.x,
                "clientY": p.y-200
            }
        };
        this.app.confirm("infor", event, MWF.xApplication.process.Xform.LP.retractTitle, MWF.xApplication.process.Xform.LP.retractText, 300, 120, function(){
            _self.app.content.mask({
                "style": {
                    "background-color": "#999",
                    "opacity": 0.6
                }
            });

            MWF.require("MWF.widget.Mask", function(){
                _self.mask = new MWF.widget.Mask({"style": "desktop", "zIndex": 50000});
                _self.mask.loadNode(_self.app.content);

                _self.fireEvent("beforeRetract");

                _self.doRetractWork(function(){
                    _self.workAction.getJobByWork(function(workJson){
                        _self.fireEvent("afterRetract");
                        _self.app.notice(MWF.xApplication.process.Xform.LP.workRetract, "success");
                        _self.app.content.unmask();
                        _self.app.reload(workJson.data);
                    }, null, _self.businessData.work.id);
                    this.close();
                    if (_self.mask) {_self.mask.hide(); _self.mask = null;}
                }.bind(this));
            }.bind(this), function(xhr, text, error){
                var errorText = error+":"+text;
                if (xhr) errorText = xhr.responseText;
                _self.app.notice("request json error: "+errorText, "error", dlg.node);
                if (_self.mask) {_self.mask.hide(); _self.mask = null;}
            });

            //this.close();
        }, function(){
            this.close();
        });
    },
    doRetractWork: function(success, failure){
        if (this.businessData.control["allowRetract"]){
            this.workAction.retractWork(function(json){
                if (success) success();
            }.bind(this), function(xhr, text, error){
                if (failure) failure(xhr, text, error);
            }, this.businessData.work.id);
        }else{
            if (failure) failure(null, "Permission Denied", "");
        }
    },
    addRetractMessage: function(data){
        var users = [];
        data.taskList.each(function(task){
            users.push(task.person+"("+task.department+")");
        }.bind(this));
        var content = "<div><b>"+MWF.xApplication.process.Xform.LP.currentActivity+"<font style=\"color: #ea621f\">"+data.work.activityName+"</font>, "+MWF.xApplication.process.Xform.LP.nextUser+"<font style=\"color: #ea621f\">"+users.join(", ")+"</font></b></div>"

        var msg = {
            "subject": MWF.xApplication.process.Xform.LP.workRetract,
            "content": "<div>"+MWF.xApplication.process.Xform.LP.retractWorkInfor+"“"+this.businessData.work.title+"”</div>"+content
        };
        layout.desktop.message.addTooltip(msg);
        return layout.desktop.message.addMessage(msg);
    },

    rerouteWork: function(e, ev){
        if (!this.businessData.control["allowReroute"]){
            MWF.xDesktop.notice("error", {x: "right", y:"top"}, "Permission Denied");
            return false;
        }
        MWF.require("MWF.xDesktop.Dialog", function(){
            var width = 480;
            var height = 160;
            var p = MWF.getCenterPosition(this.app.content, width, height);

            var _self = this;
            var dlg = new MWF.xDesktop.Dialog({
                "title": this.app.lp.reroute,
                "style": "work",
                "top": p.y-100,
                "left": p.x,
                "fromTop": p.y-100,
                "fromLeft": p.x,
                "width": width,
                "height": height,
                "url": this.app.path+"reroute.html",
                "container": this.app.content,
                "isClose": true,
                "onPostShow": function(){
                    $("rerouteWork_okButton").addEvent("click", function(){
                        _self.doRerouteWork(this);
                    }.bind(this));
                    $("rerouteWork_cancelButton").addEvent("click", function(){
                        this.close();
                    }.bind(this));

                    var select = $("rerouteWork_selectActivity");
                    _self.workAction.getRerouteTo(_self.businessData.work.process, function(json){
                        json.data.agentList.each(function(activity){
                            new Element("option", {
                                "value": activity.id+"#agent",
                                "text": activity.name
                            }).inject(select);
                        }.bind(_self));

                        json.data.cancelList.each(function(activity){
                            new Element("option", {
                                "value": activity.id+"#cancel",
                                "text": activity.name
                            }).inject(select);
                        }.bind(_self));

                        json.data.choiceList.each(function(activity){
                            new Element("option", {
                                "value": activity.id+"#choice",
                                "text": activity.name
                            }).inject(select);
                        }.bind(_self));

                        json.data.conditionList.each(function(activity){
                            new Element("option", {
                                "value": activity.id+"#condition",
                                "text": activity.name
                            }).inject(select);
                        }.bind(_self));

                        json.data.delayList.each(function(activity){
                            new Element("option", {
                                "value": activity.id+"#delay",
                                "text": activity.name
                            }).inject(select);
                        }.bind(_self));

                        json.data.embedList.each(function(activity){
                            new Element("option", {
                                "value": activity.id+"#embed",
                                "text": activity.name
                            }).inject(select);
                        }.bind(_self));

                        json.data.endList.each(function(activity){
                            new Element("option", {
                                "value": activity.id+"#end",
                                "text": activity.name
                            }).inject(select);
                        }.bind(_self));

                        json.data.invokeList.each(function(activity){
                            new Element("option", {
                                "value": activity.id+"#invoke",
                                "text": activity.name
                            }).inject(select);
                        }.bind(_self));

                        json.data.manualList.each(function(activity){
                            new Element("option", {
                                "value": activity.id+"#manual",
                                "text": activity.name
                            }).inject(select);
                        }.bind(_self));

                        json.data.mergeList.each(function(activity){
                            new Element("option", {
                                "value": activity.id+"#merge",
                                "text": activity.name
                            }).inject(select);
                        }.bind(_self));

                        json.data.messageList.each(function(activity){
                            new Element("option", {
                                "value": activity.id+"#message",
                                "text": activity.name
                            }).inject(select);
                        }.bind(_self));

                        json.data.parallelList.each(function(activity){
                            new Element("option", {
                                "value": activity.id+"#parallel",
                                "text": activity.name
                            }).inject(select);
                        }.bind(_self));

                        json.data.serviceList.each(function(activity){
                            new Element("option", {
                                "value": activity.id+"#service",
                                "text": activity.name
                            }).inject(select);
                        }.bind(_self));

                        json.data.splitList.each(function(activity){
                            new Element("option", {
                                "value": activity.id+"#split",
                                "text": activity.name
                            }).inject(select);
                        }.bind(_self));
                    }.bind(_self));
                }
            });
            dlg.show();
        }.bind(this));
    },
    doRerouteWork: function(dlg){
        var opinion = $("rerouteWork_opinion").get("value");
        var select = $("rerouteWork_selectActivity");
        var activity = select.options[select.selectedIndex].get("value");
        var activityName = select.options[select.selectedIndex].get("text");
        var tmp = activity.split("#");
        activity = tmp[0];
        var type = tmp[1];

        MWF.require("MWF.widget.Mask", function(){
            this.mask = new MWF.widget.Mask({"style": "desktop", "zIndex": 50000});
            this.mask.loadNode(this.app.content);

            this.fireEvent("beforeReroute");

            this.rerouteWorkToActivity(activity, type, opinion, function(){
                this.workAction.getJobByWork(function(workJson){
                    this.fireEvent("afterReroute");
                    this.addRerouteMessage(workJson.data);
                    this.app.notice(MWF.xApplication.process.Xform.LP.rerouteOk+": "+activityName, "success");
                    this.app.close();
                }.bind(this), null, this.businessData.work.id);
                dlg.close();
                if (this.mask) {this.mask.hide(); this.mask = null;}
            }.bind(this), function(xhr, text, error){
                var errorText = error+":"+text;
                if (xhr) errorText = xhr.responseText;
                this.app.notice("request json error: "+errorText, "error", dlg.node);
                if (this.mask) {this.mask.hide(); this.mask = null;}
            }.bind(this));
        }.bind(this));
    },
    rerouteWorkToActivity: function(activity, type, opinion, success, failure){
        if (this.businessData.task){
            this.workAction.saveData(function(json){
                this.workAction.rerouteWork(function(json){
                    if (success) success();
                }.bind(this), function(xhr, text, error){
                    if (failure) failure(xhr, text, error);
                }, this.businessData.work.id, activity, type);
            }.bind(this), function(xhr, text, error){
                if (failure) failure(xhr, text, error);
            }, this.businessData.work.id, this.getData());
        }else{
            this.workAction.rerouteWork(function(json){
                if (success) success();
            }.bind(this), function(xhr, text, error){
                if (failure) failure(xhr, text, error);
            }, this.businessData.work.id, activity, type);
        }
    },
    addRerouteMessage: function(data){
        var users = [];
        data.taskList.each(function(task){
            users.push(task.person+"("+task.department+")");
        }.bind(this));
        var content = "<div><b>"+MWF.xApplication.process.Xform.LP.currentActivity+"<font style=\"color: #ea621f\">"+data.work.activityName+"</font>, "+MWF.xApplication.process.Xform.LP.nextUser+"<font style=\"color: #ea621f\">"+users.join(", ")+"</font></b></div>"

        var msg = {
            "subject": MWF.xApplication.process.Xform.LP.workReroute,
            "content": "<div>"+MWF.xApplication.process.Xform.LP.rerouteWorkInfor+"“"+this.businessData.work.title+"”</div>"+content
        };
        layout.desktop.message.addTooltip(msg);
        return layout.desktop.message.addMessage(msg);
    },

    deleteWork: function(){
        var _self = this;
        var p = MWF.getCenterPosition(this.app.content, 380, 150);
        var event = {
            "event":{
                "x": p.x,
                "y": p.y-200,
                "clientX": p.x,
                "clientY": p.y-200
            }
        };
        this.app.confirm("infor", event, MWF.xApplication.process.Xform.LP.deleteWorkTitle, MWF.xApplication.process.Xform.LP.deleteWorkText, 380, 120, function(){
            //_self.app.content.mask({
            //    "style": {
            //        "background-color": "#999",
            //        "opacity": 0.6
            //    }
            //});


            MWF.require("MWF.widget.Mask", function(){
                _self.mask = new MWF.widget.Mask({"style": "desktop", "zIndex": 50000});
                _self.mask.loadNode(_self.app.content);

                _self.fireEvent("beforeDelete");

                _self.doDeleteWork(function(){
                    _self.app.notice(MWF.xApplication.process.Xform.LP.workDelete+": “"+_self.businessData.work.title+"”", "success");
                    _self.app.close();
                    this.close();
                    if (_self.mask) {_self.mask.hide(); _self.mask = null;}
                }.bind(this),function(xhr, text, error){
                    var errorText = error+":"+text;
                    if (xhr) errorText = xhr.responseText;
                    _self.app.notice("request json error: "+errorText, "error", dlg.node);
                    if (_self.mask) {_self.mask.hide(); _self.mask = null;}
                }.bind(this));
            }.bind(this));



            //_self.workAction.deleteWork(function(json){
            //    _self.app.notice(MWF.xApplication.process.Xform.LP.workDelete+": “"+_self.businessData.work.title+"”", "success");
            //    _self.app.close();
            //    this.close();
            //}.bind(this), null, _self.businessData.work.id);
            //this.close();
        }, function(){
            this.close();
        });
    },
    doDeleteWork: function(success, failure){
        if (this.businessData.control["allowDelete"]){
            this.workAction.deleteWork(function(json){
                if (success) success();
            }.bind(this), function(xhr, text, error){
                if (failure) failure(xhr, text, error);
            }, this.businessData.work.id);
        }else{
            if (failure) failure(null, "Permission Denied", "");
        }
    },

    //printWork: function(){
    //    var form = this.json.id;
    //    if (this.json.printForm){
    //        form = this.json.printForm;
    //    }
    //    window.open("/x_desktop/printWork.html?workid="+this.businessData.work.id+"&app="+this.businessData.work.application+"&form="+form);
    //},
    printWork: function(app, form){
        var application = app || (this.businessData.work) ? this.businessData.work.application : this.businessData.workCompleted.application;
        var form = form;
        if (!form){
            form = this.json.id;
            if (this.json.printForm) form = this.json.printForm;
        }
        if (this.businessData.workCompleted){
            var application = app || this.businessData.workCompleted.application;
            window.open("/x_desktop/printWork.html?workCompletedId="+this.businessData.workCompleted.id+"&app="+application+"&form="+form);
        }else{
            var application = app || this.businessData.work.application;
            window.open("/x_desktop/printWork.html?workid="+this.businessData.work.id+"&app="+application+"&form="+form);
        }

    },
    openWindow: function(form, app){
        //var application = app || (this.businessData.work) ? this.businessData.work.application : this.businessData.workCompleted.application;
        var form = form;
        if (!form){
            form = this.json.id;
            //if (this.json.printForm) form = this.json.printForm;
        }
        if (this.businessData.workCompleted){
            var application = app || this.businessData.workCompleted.application;
            window.open("/x_desktop/printWork.html?workCompletedId="+this.businessData.workCompleted.id+"&app="+application+"&form="+form);
        }else{
            var application = app || this.businessData.work.application;
            window.open("/x_desktop/printWork.html?workid="+this.businessData.work.id+"&app="+application+"&form="+form);
        }
        //window.open("/x_desktop/printWork.html?workid="+this.businessData.work.id+"&app="+this.businessData.work.application+"&form="+form);
    },

    uploadedAttachment: function(site, id){
        this.workAction.getAttachment(id, this.businessData.work.id, function(json){
            var att = this.all[site];
            if (att){
                if (json.data) att.attachmentController.addAttachment(json.data);
                att.attachmentController.checkActions();
                att.fireEvent("upload", [json.data]);
            }
        }.bind(this));
    },
    replacedAttachment: function(site, id){
        this.workAction.getAttachment(id, this.businessData.work.id, function(json){

            var att = this.all[site];
            if (att){
                var attachmentController = att.attachmentController;
                var attachment = null;
                for (var i=0; i<attachmentController.attachments.length; i++){
                    if (attachmentController.attachments[i].data.id===id){
                        attachment = attachmentController.attachments[i];
                        break;
                    }
                }
                attachment.data = json.data;
                attachment.reload();
                attachmentController.checkActions();
            }
        }.bind(this))
    }
	
});